import React, { Component } from 'react';
import { Table } from 'antd';
import { connect } from 'dva';

@connect(({ loading, addempsend }) => ({
  loading: loading.effects['addempsend/getSecond'],
  addempsend,
}))
class AssociationTable extends Component {
  shouldComponentUpdate(nextProps) {
    const { businessData } = this.props;
    if (
      JSON.stringify(businessData) !== JSON.stringify(nextProps.businessData) &&
      nextProps.businessData.length
    ) {
      this.handlePaginationData({
        data: nextProps.businessData,
        current: nextProps.addempsend.dataList.pagination.current,
        pageSize: nextProps.addempsend.dataList.pagination.pageSize,
      });
    }
    return true;
  }

  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'addempsend/updateModelData',
      payload: {
        dataList: {
          list: [],
          pagination: {
            current: 1,
            pageSize: 10,
            total: 10,
          },
        },
        businessData: [],
      },
    });
  }

  handleTableChange = pagination => {
    const { businessData } = this.props;
    this.handlePaginationData({
      data: businessData,
      current: pagination.current,
      pageSize: pagination.pageSize,
    });
  };

  handlePaginationData = params => {
    const { dispatch } = this.props;
    dispatch({
      type: 'addempsend/handlePaginationData',
      payload: {
        data: params.data,
        current: params.current,
        pageSize: params.pageSize,
      },
    });
  };

  render() {
    const {
      addempsend: { dataList },
      columns,
      tableLoading,
    } = this.props;
    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      showTotal: total => {
        const totalPage =
          total < dataList.pagination.pageSize
            ? 1
            : Math.ceil(total / dataList.pagination.pageSize);
        return `共 ${total} 条记录 第 ${dataList.pagination.current} / ${totalPage}页`;
      },
      ...dataList.pagination,
    };
    return (
      <Table
        loading={tableLoading}
        dataSource={dataList.list}
        rowKey={(rowKey, index) => index}
        columns={columns}
        rowSelection={null}
        pagination={paginationProps}
        onChange={this.handleTableChange}
      />
    );
  }
}

export default AssociationTable;
